package com.ssy.lingxi.member.merchant.handler.converter;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.member.merchant.model.bo.AgentAreaBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**将自定义的省市区域Entity，与表中的Jsonb字段进行转换
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-20
 */
@Converter(autoApply = true)
public class JpaJsonToAgentAreaBOConverter implements AttributeConverter<AgentAreaBO, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public JpaJsonToAgentAreaBOConverter() {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public String convertToDatabaseColumn(AgentAreaBO attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"代理省市转换Json错误");
        }
    }

    @Override
    public AgentAreaBO convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new AgentAreaBO();
            }

            return OBJECT_MAPPER.readValue(dbData, AgentAreaBO.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换省市区域实体错误");
        }
    }
}
